<?php
/**
 * Created by PhpStorm.
 * User: CCA
 * Date: 2019/10/10
 * Time: 10:09
 */

namespace app\api\controller;


use app\api\BaseController;
use app\common\model\Member;
use app\common\model\Token;
use think\Lang;
use think\Request;
use RongCloud\RongCloud;


/**
 * @title 用户
 * @description 用户相关
 */
class Round extends BaseController
{

    const   SERVERAPIURL = 'http://api.cn.ronghub.com';    //请求服务地址

    public function __construct(){
        $this->appKey = 'lmxuhwaglemtd';
        $this->appSecret = 'GK3Ta4syTKezax';
        $this->format = 'json';

        $this->RongCloud = new RongCloud($this->appKey,$this->appSecret);
        $this->user = $this->RongCloud->getUser();//用户对象
        $this->message = $this->RongCloud->getMessage()->Person();//消息对象
        $this->check = $this->RongCloud->getUser()->Onlinestatus();//检查用户状态
    }

    #融云获取token
    public function roundToken(){

        if(empty(input('post.userId')))
            return json_fail_return('用户 Id 不能为空');
        if(empty(input('post.name')))
            return json_fail_return('用户名称 不能为空');
        if(empty(input('post.portraitUri')))
            return json_fail_return('用户头像 URI 不能为空');

        #通过sdk
        $res = $this->user->register(array('id'=>input('post.userId'),'name'=>input('post.name'),'portrait'=>input('post.portraitUri')));

        #通过直接请求
        // $ret = $this->curl('/user/getToken',array('userId'=>input('post.userId'),'name'=>input('post.name'),'portraitUri'=>input('post.portraitUri')));

        return json_success_return($res);   
    }

        /**
     * 单聊 一个用户向另外一个用户发送消息。
     * @return json|xml
     */
    public function messagePublish() {
        $fromUserId =  input('post.UserId');
        $toUserId =  input('post.toUserId');
        
        $content =  input('post.content');
        
        if(empty($fromUserId))
            return json_fail_return('发送人用户 Id 不能为空');
        if(empty($toUserId))
            return json_fail_return('接收用户 Id 不能为空');
        if(empty($content))
            return json_fail_return('发送消息内容 不能为空');

        $params = array(
            'senderId'=>$fromUserId,
            'targetId' => $toUserId,
            'objectName'=>'TxtMsg',
            'content'=>json_encode($content)
        );
        
        #sdk
        $res = $this->message->send($params);

        #直接请求
        // $ret = $this->curl('/message/private/publish', $params);
        return json_success_return($res);   
        
    }

    /**
     * 检查用户在线状态 方法
     * @param $userId    用户 Id。（必传）  在线状态，1为在线，0为不在线。
     * @return mixed
     */
    public function userCheckOnline() {
        $userId =  input('post.UserId');
        if(empty($userId))
            return json_fail_return('用户 Id 不能为空');
 
        #sdk
        $ret = $this->check->check(array('id'=>$userId));

        // $ret = $this->curl('/user/checkOnline', array('userId' => $userId));
        
        return json_success_return($ret); 
    }

     /**
     * 创建http header参数
     * @param array $data
     * @return bool
     */
    private function createHttpHeader() {

        #生成签名
        $appSecret = 'GK3Ta4syTKezax'; 
        $nonce = rand(); // 获取随机数。
        $timestamp = time()*1000; // 获取时间戳（毫秒）。

        $signature = sha1($appSecret.$nonce.$timestamp);

        return array(
            'App-Key:'.'lmxuhwaglemtd',
            'Nonce:'.$nonce,
            'Timestamp:'.$timestamp,
            'Signature:'.$signature,
        );

    }
    /**
     * 重写实现 http_build_query 提交实现(同名key)key=val1&key=val2
     * @param array $formData 数据数组
     * @param string $numericPrefix 数字索引时附加的Key前缀
     * @param string $argSeparator 参数分隔符(默认为&)
     * @param string $prefixKey Key 数组参数，实现同名方式调用接口
     * @return string
     **/
    private function build_query($formData, $numericPrefix = '', $argSeparator = '&', $prefixKey = '') {
        $str = '';
        foreach ($formData as $key => $val) {
            if (!is_array($val)) {
                $str .= $argSeparator;
                if ($prefixKey === '') {
                    if (is_int($key)) {
                        $str .= $numericPrefix;
                    }
                    $str .= urlencode($key) . '=' . urlencode($val);
                } else {
                    $str .= urlencode($prefixKey) . '=' . urlencode($val);
                }
            } else {
                if ($prefixKey == '') {
                    $prefixKey .= $key;
                }
                if (is_array($val[0])) {
                    $arr = array();
                    $arr[$key] = $val[0];
                    $str .= $argSeparator . http_build_query($arr);
                } else {
                    $str .= $argSeparator . $this->build_query($val, $numericPrefix, $argSeparator, $prefixKey);
                }
                $prefixKey = '';
            }
        }
        return substr($str, strlen($argSeparator));
    }


    public function curl($action, $params,$contentType='urlencoded') {
        $action = self::SERVERAPIURL.$action.'.'.$this->format;
        $httpHeader = $this->createHttpHeader();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $action);
        curl_setopt($ch, CURLOPT_POST, 1);
        if ($contentType=='urlencoded') {
            $httpHeader[] = 'Content-Type:application/x-www-form-urlencoded';
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->build_query($params));
        }
        if ($contentType=='json') {
            $httpHeader[] = 'Content-Type:Application/json';
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params) );
        }
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); //处理http证书问题
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $ret = curl_exec($ch);
        if (false === $ret) {
            $ret =  curl_errno($ch);
        }
        curl_close($ch);
        return $ret;
    }


    
    /**
     * 检查用户信息
     * @param $userId    用户 Id。（必传）  在线状态，1为在线，0为不在线。
     * @return mixed
     */
    public function userInfo() {
        $userId =  input('post.UserId');
        if(empty($userId))
            return json_fail_return('用户 Id 不能为空');
        $ret = $this->curl('/user/info', array('userId' => $userId));
        
        return $ret;
    }



    
    #消息撤回
    public function messageRecall() {
        $fromUserId =  input('post.fromUserId');
        $conversationType =  input('post.conversationType');
        $targetId =  input('post.targetId');
        $messageUID =  input('post.messageUID');
        $sentTime =  input('post.sentTime');
        
        if(empty($fromUserId))
            return json_fail_return('发送人用户 Id 不能为空');
        if(empty($conversationType))
            return json_fail_return('会话类型不能为空');

        $params = array(
            'fromUserId'=>$fromUserId,
            'conversationType'=>$conversationType,
            'targetId'=>$targetId,
            'messageUID'=>$messageUID,
            'sentTime'=>$sentTime,
        );

        $ret = $this->curl('/message/recall', $params);

        return json_success_return($ret);   
    }

    #消息历史记录
    public function messageHistory() {
        $date =  input('post.date');
        
        if(empty($date))
            return json_fail_return('日期 不能为空');
        
        $params = array(
            'date'=>$date,
        );

        $ret = $this->curl('/message/history', $params);

        return json_success_return($ret);   
    }

}